package com.wn.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wn.entity.User;
import com.wn.mapper.UserMapper;
import com.wn.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * ServiceImpl MP提供的通用service实现
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

   /* @Override
    public int updateAccount() {
        // 同步锁：获取锁的线程才可以操作同步代码块
        // synchronized悲观锁：总是认为这个数据会备别人修改，所以操作之前先加锁。
        synchronized (this) {
            User user = this.baseMapper.selectById(1);
            user.setBalance(user.getBalance() - 10);
            int effectRow = this.baseMapper.updateById(user);
            log.info("受影响的行数：" + effectRow);
            return effectRow;
        }
    }*/

    @Override
    public int updateAccount() {
        User user = this.baseMapper.selectById(1);
        user.setBalance(user.getBalance() - 10);
        int effectRow = this.baseMapper.updateById(user);
        log.info("受影响的行数：" + effectRow);

        while (effectRow == 0) { // 自旋：受影响的行数为0，修改失败，继续执行业务；
            user = this.baseMapper.selectById(1);
            user.setBalance(user.getBalance() - 10);
            effectRow = this.baseMapper.updateById(user);
            log.info("受影响的行数：" + effectRow);
        }

        return effectRow;
    }
}